import React, {useEffect, useState} from 'react'
import {
    Form,
    Select,
    Input,
    Button,
    Row,
    Col,
    Space,
    message,
    Typography
} from 'antd';
import {FileExcelOutlined, StepBackwardOutlined} from '@ant-design/icons';
import backgroundImage from '../images/form_bg@2x.2d429e6ecd7d2c432e6f.png';
import {request} from "../utils/requset";
import {useSelector} from "react-redux";
import {useNavigate} from "react-router-dom";


const backgroundStyle = {
    backgroundImage: `url(${backgroundImage})`,
    backgroundSize: 'cover', // 使背景图片覆盖整个容器
    backgroundPosition: 'center', // 背景图片居中
    backgroundRepeat: 'no-repeat', // 防止背景图片重复
    // minHeight: '100vh', // 确保背景图片覆盖整个视口高度
    // 其他您需要的样式
};


const {Option} = Select;
const {Title, Text} = Typography;

const OperatePage = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [runLoading, setRunLoading] = useState(false);
    const [clearLoading, setClearLoading] = useState(false);
    const [rowDefineReady, setRowDefineReady] = useState(false);
    const [columnDefineReady, setColumnDefineReady] = useState(false);
    const [szyReady, setSzyReady] = useState(false);
    const [szyMxReady, setSzyMxReady] = useState(false);

    const sysConfig = useSelector(state => state.pz.sysConfig);


    const navigator = useNavigate();

    useEffect(() => {
        form.setFieldsValue({
            model: sysConfig.model,
            qzq_type: sysConfig.qzq_type,
            need_report_desc: sysConfig.need_report_desc
        })
        // 刷新前置条件状态
        handleCheckRowDefineReady();
        handleCheckColumnDefineReady();
        // 刷新报表检查状态
        handleCheckSzyReady();
        handleCheckSzyMxReady();
    }, [sysConfig])


    const handleCheckRowDefineReady = async () => {
        try {

            setLoading(true);
            const response = await request.post('/nw_szy_mx/api/check_row_define_ready',{
                dwbh: sysConfig.dwbh,
                model: sysConfig.model,
                qzq_type: sysConfig.qzq_type
            });
            const data = response.data;
            // console.log(data)
            // console.log(data ? data.code : 500)
            if (data && data.code === 200) {
                console.log(data.data)
                if(data.data === 1){
                    setRowDefineReady(true);
                }else{
                    setRowDefineReady(false);
                }
            } else if (data && data.message) {
                setRowDefineReady(false);
                message.error(data.message);
            }

        } catch (error) {
            setRowDefineReady(false);
            if (error.response) {
                message.error(`校验失败: ${error.response.data.message?error.response.data.message:error.response.data.error}`);
            } else {
                console.error('校验失败:', error);
                message.error('校验失败，请稍后再试。');
            }
        } finally {
            setLoading(false);
        }
    };

    const handleCheckColumnDefineReady = async () => {
        try {

            setLoading(true);
            const response = await request.post('/nw_szy_mx/api/check_column_define_ready',{
                dwbh: sysConfig.dwbh,
                model: sysConfig.model
            });
            const data = response.data;
            // console.log(data)
            // console.log(data ? data.code : 500)
            if (data && data.code === 200) {
                console.log(data.data)
                if(data.data === 1){
                    setColumnDefineReady(true);
                }else{
                    setColumnDefineReady(false);
                }
            } else if (data && data.message) {
                setColumnDefineReady(false);
                message.error(data.message);
            }

        } catch (error) {
            setColumnDefineReady(false);
            if (error.response) {
                message.error(`校验失败: ${error.response.data.message?error.response.data.message:error.response.data.error}`);
            } else {
                console.error('校验失败:', error);
                message.error('校验失败，请稍后再试。');
            }
        } finally {
            setLoading(false);
        }
    };

    const handleCheckSzyReady = async () => {
        try {

            setLoading(true);
            const response = await request.post('/nw_szy/api/check_szy_ready',{
                dwbh: sysConfig.dwbh,
                model: sysConfig.model,
                qzq_type: sysConfig.qzq_type
            });
            const data = response.data;
            // console.log(data)
            // console.log(data ? data.code : 500)
            if (data && data.code === 200) {
                console.log(data.data)
                if(data.data === 1){
                    setSzyReady(true);
                }else{
                    setSzyReady(false);
                }
            } else if (data && data.message) {
                setSzyReady(false);
                message.error(data.message);
            }

        } catch (error) {
            setSzyReady(false);
            if (error.response) {
                message.error(`校验失败: ${error.response.data.message?error.response.data.message:error.response.data.error}`);
            } else {
                console.error('校验失败:', error);
                message.error('校验失败，请稍后再试。');
            }
        } finally {
            setLoading(false);
        }
    };

    const handleCheckSzyMxReady = async () => {
        try {

            setLoading(true);
            const response = await request.post('/nw_szy_mx/api/check_szy_mx_ready',{
                dwbh: sysConfig.dwbh,
                model: sysConfig.model,
                qzq_type: sysConfig.qzq_type
            });
            const data = response.data;
            // console.log(data)
            // console.log(data ? data.code : 500)
            if (data && data.code === 200) {
                console.log(data.data)
                if(data.data === 1){
                    setSzyMxReady(true);
                }else{
                    setSzyMxReady(false);
                }
            } else if (data && data.message) {
                setSzyMxReady(false);
                message.error(data.message);
            }

        } catch (error) {
            setSzyMxReady(false);
            if (error.response) {
                message.error(`校验失败: ${error.response.data.message?error.response.data.message:error.response.data.error}`);
            } else {
                console.error('校验失败:', error);
                message.error('校验失败，请稍后再试。');
            }
        } finally {
            setLoading(false);
        }
    };
    const handleCalc = async () => {
        try {
            setLoading(true);

            const values = await form.validateFields();
            // console.log(values)
            const payload = {
                dwbh: sysConfig.dwbh,
                ledger: sysConfig.ledger,
                model: values.model,
                qzq_type: values.qzq_type
            };
            /*
            
            */
            await request.post('/nw_szy_mx/api/calc_szy', payload);
            // 刷新报表检查状态
            await handleCheckSzyReady();
            setLoading(true);
            await request.post('/nw_szy_mx/api/calc_szy_mx', payload);
            // 刷新报表检查状态
            await handleCheckSzyMxReady();
            message.success('报表计算完成！');
        } catch (error) {
            if (error.response) {
                message.error(`报表计算失败: ${error.response.data.message?error.response.data.message:error.response.data.error}`);
            } else {
                // console.error(':', error);
                message.error('报表计算失败');
            }
        } finally {
            setLoading(false);
        }
    };

    const handleDownload = async () => {
        try {

            const values = await form.validateFields();
            const payload = {
                dwbh: sysConfig.dwbh,
                ledger: sysConfig.ledger,
                model: values.model,
                qzq_type: values.qzq_type,
                need_report_desc: values.need_report_desc
            };
            setRunLoading(true);


            const response = await request.post('/nw_szy/api/download', payload, {
                responseType: 'blob' // 设置响应类型为 blob，以便处理文件下载
            });
            // 从响应头中提取文件名
            const contentDisposition = response.headers['content-disposition'];
            const fileName = contentDisposition
                ? contentDisposition.split('filename=')[1].replace(/"/g, '') // 解析文件名
                : 'downloaded_file.xlsx';  // 默认文件名

            // 创建一个链接并模拟点击下载 Excel 文件
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);  // 文件名
            document.body.appendChild(link);
            link.click();

            // 清理 URL 对象
            link.parentNode.removeChild(link);
            message.success('报表下载完成！');
        } catch (error) {
            if (error.response) {
                console.log(error)
                error.response.data.text().then()
                console.log()
                message.error(`报表下载失败: ${error.response.data.message}`);
            } else {
                // console.error(':', error);
                message.error('报表下载失败');
            }
        } finally {
            setRunLoading(false);
        }
    };

    const handleMxDownload = async () => {
        try {

            const values = await form.validateFields();
            const payload = {
                dwbh: sysConfig.dwbh,
                ledger: sysConfig.ledger,
                model: values.model,
                qzq_type: values.qzq_type
            };
            setRunLoading(true);


            const response = await request.post('/nw_szy_mx/api/download', payload, {
                responseType: 'blob' // 设置响应类型为 blob，以便处理文件下载
            });
            // 从响应头中提取文件名
            const contentDisposition = response.headers['content-disposition'];
            const fileName = contentDisposition
                ? contentDisposition.split('filename=')[1].replace(/"/g, '') // 解析文件名
                : 'downloaded_file_mx.xlsx';  // 默认文件名

            // 创建一个链接并模拟点击下载 Excel 文件
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);  // 文件名
            document.body.appendChild(link);
            link.click();

            // 清理 URL 对象
            link.parentNode.removeChild(link);
            message.success('报表下载完成！');
        } catch (error) {
            if (error.response) {
                message.error(`报表下载失败: ${error.response.data.message}`);
            } else {
                // console.error(':', error);
                message.error('报表下载失败');
            }
        } finally {
            setRunLoading(false);
        }
    };


    const handleClearData = async () => {
        try {
            setClearLoading(true);
            // const values = await form.getFieldValue();
            const response = await request.post('/nw_szy_mx/api/clear', {
                dwbh: sysConfig.dwbh,
                ledger: sysConfig.ledger,
                model: sysConfig.model,
                qzq_type: sysConfig.qzq_type
            });
            const data = response.data;
            // console.log(data)
            // console.log(data ? data.code : 500)
            if (data && data.code == 200) {
                message.success('操作完成！');
            } else if (data && data.message) {
                message.error(data.message);
            }


        } catch (error) {
            if (error.response) {
                message.error(`操作失败: ${error.response.data.message}`);
            } else {
                // console.error('操作失败:', error);
                message.error('操作失败，请稍后再试。');
            }
        } finally {
            setClearLoading(false);
        }
    };


    return (
        <Row justify="center">

            <Col xs={24} sm={20} md={20}>
                <div className="config-page-layout float-center" style={backgroundStyle}>
                    <div className="upper-section">
                        <Title>
                            报表生成
                            {/* 保存和运行按钮 */}
                            <Space className='float-right' style={{marginBottom: 16, marginLeft: 8}}>
                                <Button type="default" onClick={()=>{navigator('/robot/rpa/nwproject')}} loading={runLoading} className='float-right'>
                                    <StepBackwardOutlined /> 报表行配置
                                </Button>
                                <Button type="default" onClick={()=>{navigator('/robot/rpa/nwfymc')}} loading={runLoading} className='float-right'>
                                    <StepBackwardOutlined /> 报表列配置
                                </Button>
                                {rowDefineReady&&columnDefineReady&&<Button type="default" onClick={handleCalc} loading={loading} className='float-right'>
                                    <FileExcelOutlined/> 生成报表
                                </Button>}
                                {szyReady&&<Button type="primary" onClick={handleDownload} loading={runLoading}
                                        className='float-right'>
                                    下载报表
                                </Button>}
                                {szyMxReady&&<Button type="primary" onClick={handleMxDownload} loading={clearLoading}
                                        className='float-right'>
                                    下载明细报表
                                </Button>}
                                {/*<Button type="primary" onClick={handleClearData} loading={clearLoading} className='float-right' danger>*/}
                                {/*    <WarningOutlined />清空数据*/}
                                {/*</Button>*/}
                            </Space>

                        </Title>
                        {(!rowDefineReady||!columnDefineReady)&&<Row gutter={16}>
                            <Text type="warning">报表行或列未配置, 请配置之后再生成报表</Text>
                        </Row>}
                        <Form
                            form={form}
                            layout="vertical"
                            initialValues={{
                                model: sysConfig.model,
                                qzq_type: sysConfig.qzq_type
                            }}
                        >

                            <Row gutter={16}>
                                {/* 模型 */}
                                <Col xs={24} sm={12} md={8}>
                                    <Form.Item
                                        label="模型"
                                        name="model"
                                        rules={[{required: true, message: '请选择模型!'}]}
                                    >
                                        <Input
                                            readOnly
                                        />
                                    </Form.Item>
                                </Col>
                                {/* 全周期类型 */}
                                <Col xs={24} sm={12} md={8}>

                                    <Form.Item
                                        label="类型"
                                        name="qzq_type"
                                        rules={[{required: true, message: '请选择全周期类型!'}]}
                                    >
                                        <Select placeholder="请选择全周期类型"
                                        >
                                            {sysConfig.qzq_type_list && sysConfig.qzq_type_list.split(',').map((item) => (
                                                <Option key={item} value={item}>
                                                    {item}
                                                </Option>
                                            ))}
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col xs={24} sm={12} md={8}>

                                    < Form.Item
                                        label="报表是否包含行列描述"
                                        name="need_report_desc"
                                        rules={[{required: true, message: "请选择至少一个选项！"}]}
                                    >
                                        <Select
                                            // mode="multiple"
                                            allowClear
                                            style={{width: "100%"}}
                                        >
                                            <Option key='是' value='是'>是</Option>
                                            <Option key='否' value='否'>否</Option>
                                        </Select>
                                    </Form.Item>
                                </Col>
                            </Row>

                        </Form>
                    </div>

                </div>
            </Col>
        </Row>
    )
}

export default OperatePage